from derbyos import NSOde
import zmq
from derbyos import DerbyXML

import wx
import wxDerbyOS


class NSOdeBrowser(wx.Frame):
    def __init__(self, nsode):
        self.nsode = nsode
        super(NSOdeBrowser, self).__init__(None, title=self.nsode.name,
                                           size=(400, 500))

        wx.StaticText(self, label="UUID:" + str(self.nsode.uuid), pos=(10, 10))
        wx.StaticText(self, label=str(self.nsode.address) + ":" + str(self.nsode.port), pos=(10, 30))
        wx.StaticLine(self, pos=(15, 50), size=(400 - 20, 1))

        self.listbox = wx.ListBox(self, -1, pos=(10, 55), size=(400 - 20, 200))

        self.noRecurseChangePeers = False

        def formatPeer(peer):
            return "%s (%s:%s)" % (peer.serviceName, peer.address, str(peer.port))

        def renamePeer(peer, attr, value):
            sel = self.nsode.peers.index(peer)  # find where the peer is in the listbox
            self.listbox.Delete(sel)
            self.listbox.Insert(formatPeer(peer), sel)

        def changePeers(obj, attr, value):
            self.listbox.Clear()
            for peer in value:
                self.listbox.Append(formatPeer(peer))
                peer.removeObserver(changePeers)
                peer.addObserver(renamePeer, "uuid")
                peer.addObserver(renamePeer, "serviceName")

        self.nsode.addObserver(changePeers, "peers")

        wx.StaticText(self, label="Name:", pos=(10, 300))
        self.namefield = wx.TextCtrl(self, 999, self.nsode.name, pos=(100, 300), size=(180, -1))

        def changeName(obj, attr, value):
            self.SetTitle(value)

        def renameNode(event):
            print event
            self.nsode.name = self.namefield.Text()

#        self.Bind(wx.EVT_TEXT, renameNode, id=999)

if __name__ == '__main__':
    wxDerbyOS.testWX("NSOde Browser", NSOdeBrowser)
    